const dayjs = require('dayjs');
const https = require('https');
const http = require('http');
module.exports = {
	timeGap(time) {
		const end = (time && time[1]) || new Date().getTime();
		const start = (time && time[0]) || null;
		if (!start) return '';
		const month = dayjs(end).diff(start, 'month');
		const year = parseInt(month / 12);
		return `${year ? year + '年' : ''}${parseInt(month % 12)}个月`;
	},
	getImgBase64(url) {
	  let base64Img;
	  return new Promise(function (resolve, reject) {
	    let req = (url.substr(0, 5) === 'https' ? https : http).get(url, function (res) {
	      let chunks = [];
	      let size = 0;
	      res.on('data', function (chunk) {
	        chunks.push(chunk);
	        size += chunk.length; // 累加缓冲数据的长度
	      });
	      
	      res.on('end', function () {
	        // Buffer.concat()方法将chunks中的所有缓冲区对象合并为一个缓冲区对象
	        let data = Buffer.concat(chunks, size);
	        base64Img = data.toString('base64');
	        resolve({ success: true, base64Img });
	      });
	    });
	    
	    req.on('error', (e) => {
	      resolve({ success: false, errmsg: e.message });
	    });
	    
	    req.end();
	  });
	}
}